package com.cheng.spider.request;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class SingletonHttpClientBuilder {

    private static final Logger LOGGER = LoggerFactory.getLogger(SingletonHttpClientBuilder.class);

    private static final HttpClientBuilder instance = HttpClientBuilder.create();

    private static List<HttpClient> clientList = new LinkedList<>();

    private SingletonHttpClientBuilder() {
    }

    public static HttpClient build() {
        LOGGER.info("创建新httpClient");
        HttpClient client = instance.build();
        clientList.add(client);
        return client;
    }

    public static void closeAllClient() {
        clientList.forEach(client -> {
            if (client != null)
                try {
                    ((CloseableHttpClient) client).close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        });
        LOGGER.info("关闭所有httpClient");
    }
}
